<template>
  <div class="singleImageUpload2 upload-container">
    <el-upload
      :data="dataObj"
      :multiple="false"
      :show-file-list="false"
      :http-request="httpRequest"
      class="image-uploader"
      drag
      action="#"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">拖拽或<em>点击上传</em></div>
    </el-upload>
    <div v-show="imageUrl.length > 0" class="image-preview">
      <div v-show="imageUrl.length > 1" class="image-preview-wrapper">
        <img :src="imageUrl" />
        <div class="image-preview-action" @click="rmImg">
          <el-icon><Delete /></el-icon>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import { apiUpload } from '@/api/upload';

export default defineComponent({
  name: 'SingleImageUpload2',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tempUrl: '',
      dataObj: { token: '', key: '' }
    };
  },
  computed: {
    imageUrl() {
      return this.modelValue;
    }
  },
  methods: {
    rmImage() {
      this.emitInput('');
    },
    emitInput(val) {
      this.$emit('update:modelValue', val);
    },
    httpRequest(options) {
      apiUpload(options.file)
        .then((response) => {
          console.log(response.data)
          this.tempUrl = response.data;
          this.emitInput(this.tempUrl);
        })
        .catch(() => {});
    },
    rmImg() {
      this.emitInput('');
    }
  }
});
</script>

<style lang="scss" scoped>
.upload-container {
  height: 146px;
  width: 146px;
  position: relative;
  .image-uploader {
    height: 146px;
    width: 146px;
    ::v-deep(.el-upload, .el-upload-dragger) {
        width: 100%;
        height: 100%;
    }
  }
  .image-preview {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0px;
    top: 0px;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
    .image-preview-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      img {
        width: 98%;
        height: 98%;
        position: absolute;
        top: 1%;
        left: 1%;
      }
    }
    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      border-radius: 8px;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.5);
      transition: opacity 0.3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;
      .el-icon-delete {
        font-size: 36px;
      }
    }
    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
}
</style>
